package com.ruoyi.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.ErrorCode;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ExceptionCast;
import com.ruoyi.common.utils.IMTokenService;
import com.ruoyi.common.utils.SendSmsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ImUser;
import com.ruoyi.system.domain.ImUserGroup;
import com.ruoyi.system.domain.ImUserMessage;
import com.ruoyi.system.im.TencentCloudImUtil;
import com.ruoyi.system.mapper.ImUserGroupMapper;
import com.ruoyi.system.mapper.ImUserMapper;
import com.ruoyi.system.mapper.ImUserMessageMapper;
import com.ruoyi.system.service.ImLoginService;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ImLoginServiceImpl implements ImLoginService {

    @Autowired
    private ImUserMapper imUserMapper;

    @Autowired
    private IMTokenService imTokenService;

    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    @Autowired
    private ImUserMessageMapper imUserMessageMapper;

    @Autowired
    private ImUserGroupMapper imUserGroupMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Map<String, Object> imLogin(LoginBody loginBody) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(loginBody.getUsername()) || StringUtils.isEmpty(loginBody.getPassword())) {
            ExceptionCast.cast(ErrorCode.USERNAME_PASSWORD_IS_NULL);
        }
        LambdaQueryWrapper<ImUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(ImUser::getUserId, loginBody.getUsername());
        ImUser imUser = imUserMapper.selectOne(userLambdaQueryWrapper);
        if (ObjectUtils.isEmpty(imUser)) {
            ExceptionCast.cast(ErrorCode.USERNAME_PASSWORD_IS_ERROR);
        }
        if (!imUser.getPassword().equals(loginBody.getPassword())) {
            ExceptionCast.cast(ErrorCode.USERNAME_PASSWORD_IS_ERROR);
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(imUser.getId());
        loginUser.setUser(new SysUser());
        String token = imTokenService.createToken(loginUser);

        String txCloudUserSig = tencentCloudImUtil.getUserSig(loginBody.getUsername());

        Map<String, Object> map = new HashMap<>();
        map.put("token", "Bearer " + token);
        map.put("user", imUser);
        map.put("sign", txCloudUserSig);
        return map;
    }

    @Override
    public void imDeleteUser(LoginBody loginBody) {
        tencentCloudImUtil.deleteUser(loginBody.getUsername());

        LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        imUserLambdaQueryWrapper.eq(ImUser::getUserId, loginBody.getUsername());
        ImUser imUser = imUserMapper.selectOne(imUserLambdaQueryWrapper);
        imUserMapper.deleteById(imUser.getId());
        //用户聊天记录全删了
        LambdaQueryWrapper<ImUserMessage> imUserMessageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        imUserMessageLambdaQueryWrapper.eq(ImUserMessage::getFromUserId, loginBody.getUsername())
                .or()
                .eq(ImUserMessage::getToUserId, loginBody.getUsername());
        imUserMessageMapper.delete(imUserMessageLambdaQueryWrapper);
        //群也删了
        LambdaQueryWrapper<ImUserGroup> userGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userGroupLambdaQueryWrapper.eq(ImUserGroup::getOwnerId, imUser.getUserId());
        imUserGroupMapper.delete(userGroupLambdaQueryWrapper);
    }

    @Override
    public AjaxResult imRegister(SendSmsUtil.SendSmsRequest request) {
        Map<String, Object> map = new HashMap<>();
        String countryCode = request.getCountryCode();
        if (!countryCode.contains("+")) {
            countryCode = "+" + countryCode;
        }

        String key = "dl" + request.getPhone();
        String code = redisCache.getCacheObject(key);
        if (ObjectUtils.isEmpty(code)) {
            return AjaxResult.error("验证码已失效");
        }
        if (ObjectUtils.isNotEmpty(request.getCode()) && code.equals(request.getCode())) {
            //验证码正确 判断用户是否注册过
            LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            imUserLambdaQueryWrapper.eq(ImUser::getCountryCode, countryCode);
            imUserLambdaQueryWrapper.eq(ImUser::getPhoneNumber, request.getPhone());
            ImUser imUser = imUserMapper.selectOne(imUserLambdaQueryWrapper);
            if (ObjectUtils.isNotEmpty(imUser)) {
//            return AjaxResult.error("该手机号已注册");
                //直接登录
                LoginUser loginUser = new LoginUser();
                loginUser.setUserId(imUser.getId());
                loginUser.setUser(new SysUser());
                String token = imTokenService.createToken(loginUser);

                String txCloudUserSig = tencentCloudImUtil.getUserSig(imUser.getUserId());

                map.put("token", "Bearer " + token);
                map.put("user", imUser);
                map.put("sign", txCloudUserSig);
                return AjaxResult.success(map);

            } else {
                //新增新用户
                String s = tencentCloudImUtil.accountImport(request.getPhone(), request.getPhone());
                Map maps = JSON.parseObject(s, Map.class);

                if ("OK".equals(maps.get("ActionStatus"))) {
                    ImUser user = new ImUser();
                    user.setCountryCode(countryCode);
                    user.setPhoneNumber(request.getPhone());
                    user.setUserId(request.getPhone());
//                    user.setPassword(request.getPassword());
                    user.setNickName(request.getPhone());
                    user.setCreateTime(new Date());
                    imUserMapper.insert(user);

                    LoginUser loginUser = new LoginUser();
                    loginUser.setUserId(user.getId());
                    loginUser.setUser(new SysUser());
                    String token = imTokenService.createToken(loginUser);

                    String txCloudUserSig = tencentCloudImUtil.getUserSig(user.getUserId());

                    map.put("token", "Bearer " + token);
                    map.put("user", user);
                    map.put("sign", txCloudUserSig);
                    return AjaxResult.success(map);
                } else {
                    return AjaxResult.error((String) maps.get("ErrorInfo"));
                }
            }
        } else {
            return AjaxResult.error("验证码错误");
        }

    }

//    @Override
//    public AjaxResult forgetPassword(SendSmsUtil.SendSmsRequest request) {
//        String countryCode = request.getCountryCode();
//        if (!countryCode.contains("+")) {
//            countryCode = "+" + countryCode;
//        }
//        LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        imUserLambdaQueryWrapper.eq(ImUser::getCountryCode, countryCode);
//        imUserLambdaQueryWrapper.eq(ImUser::getPhoneNumber, request.getPhone());
//        ImUser imUser = imUserMapper.selectOne(imUserLambdaQueryWrapper);
//        if (ObjectUtils.isEmpty(imUser)) {
//            return AjaxResult.error("用户尚未注册");
//        }
//        String key = "mm" + request.getPhone();
//        String code = redisCache.getCacheObject(key);
//        if (ObjectUtils.isEmpty(code)) {
//            return AjaxResult.error("验证码已失效");
//        }
//        if (ObjectUtils.isNotEmpty(request.getCode()) && code.equals(request.getCode())) {
//            imUser.setPassword(request.getPassword());
//            imUserMapper.updateById(imUser);
//            return AjaxResult.success();
//        } else {
//            return AjaxResult.error("验证码错误");
//        }
//    }

    @Override
    public AjaxResult sendCode(SendSmsUtil.SendSmsRequest request) {
        String countryCode = request.getCountryCode();
        if (!countryCode.contains("+")) {
            countryCode = "+" + countryCode;
        }
//        if (request.getType() == 1) {
//            //忘记密码 判断是否注册过
//            LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            imUserLambdaQueryWrapper.eq(ImUser::getCountryCode, countryCode);
//            imUserLambdaQueryWrapper.eq(ImUser::getPhoneNumber, request.getPhone());
//            ImUser imUser = imUserMapper.selectOne(imUserLambdaQueryWrapper);
//            if (ObjectUtils.isEmpty(imUser)) {
//                return AjaxResult.error("用户未注册");
//            }
//        }
        String s = RandomUtil.randomNumbers(6);
        request.setCode(s);
        request.setCountryCode(countryCode);
        SendSmsUtil.sendSms(request);
        String key = null;
        key = "dl" + request.getPhone();
        //判断redis是否已有了 有了删除再加新的
        String cacheObject = redisCache.getCacheObject(key);
        if (ObjectUtils.isNotEmpty(cacheObject)) {
            redisCache.deleteObject(key);
        }
        redisCache.setCacheObject(key, s);
        redisCache.expire(key, 60 * 5);
        return AjaxResult.success();
    }
}
